﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows.Controls;
using System.Windows.Forms;
using System.Xml;
using System.Xml.Linq;
using YArchitech.Controls;

namespace YJKMenuAssist.Utility
{
	public class XmlManager
	{
		public XmlManager(string strXmlPathFileName)
		{
			this.m_strXmlPathFileName = strXmlPathFileName;
		}

		private XmlNode CreateXmlDocument()
		{
			this.m_xmlDoc = new XmlDocument();
			XmlDeclaration newChild = this.m_xmlDoc.CreateXmlDeclaration("1.0", "gb2312", null);
			return this.m_xmlDoc.AppendChild(newChild);
		}

		private bool SaveXmlDocument()
		{
			bool result;
			try
			{
				this.m_xmlDoc.Save(this.m_strXmlPathFileName);
				result = true;
			}
			catch
			{
				YJKMessageBox.Show("保持XmlDocument文档失败：\n", MessageBoxButtons.OK, MessageBoxIcon.Hand);
				result = false;
			}
			return result;
		}

		public bool ExportMenu2Xml(CommandTableInfos commandTableInfos)
		{
			try
			{
				this.CreateXmlDocument();
				XmlNode xmlNode = this.m_xmlDoc.CreateElement("Tabs");
				this.m_xmlDoc.AppendChild(xmlNode);
				foreach (TableInfos tableInfos in commandTableInfos.TableInofList)
				{
					XmlElement xmlElement = this.m_xmlDoc.CreateElement("Tab");
					xmlElement.SetAttribute("Name", tableInfos.TableName);
					foreach (CommandInfos commandInfos in tableInfos.CommandInfoList)
					{
						XmlElement xmlElement2 = this.m_xmlDoc.CreateElement("PushButton");
						commandInfos.Export2XmlNode(xmlElement2);
						xmlElement.AppendChild(xmlElement2);
					}
					xmlNode.AppendChild(xmlElement);
				}
				if (!this.SaveXmlDocument())
				{
					return false;
				}
			}
			catch (Exception)
			{
				YJKMessageBox.Show("创建xml文档时出错！", MessageBoxButtons.OK, MessageBoxIcon.Hand);
				return false;
			}
			return true;
		}

		public bool ExportMenuXml(System.Windows.Controls.TreeView treeView, CommandTableInfos commandTableInfos)
		{
			try
			{
				if (!this.LoadXML(this.m_strXmlPathFileName))
				{
					return false;
				}
				foreach (object obj in this.m_xmlDoc.SelectSingleNode("MYCONFIG").SelectNodes("Tabs"))
				{
					XmlNode xmlNode = (XmlNode)obj;
					if (xmlNode.Attributes["Name"].Value == "Custom")
					{
						xmlNode.RemoveAll();
						((XmlElement)xmlNode).SetAttribute("Name", "Custom");
						for (int i = 0; i < treeView.Items.Count; i++)
						{
							TreeViewItem treeViewItem = treeView.Items[i] as TreeViewItem;
							XmlElement xmlElement = this.m_xmlDoc.CreateElement("Tab");
							xmlElement.SetAttribute("Name", treeViewItem.Tag.ToString());
							this.SetXmlCmd(treeViewItem, xmlElement);
							xmlNode.AppendChild(xmlElement);
						}
					}
				}
				if (!this.SaveXmlDocument())
				{
					return false;
				}
				this.ModifyXML(treeView, commandTableInfos);
			}
			catch (Exception)
			{
				YJKMessageBox.Show("创建xml文档时出错！", MessageBoxButtons.OK, MessageBoxIcon.Hand);
				return false;
			}
			return true;
		}

		public List<string> ReadMenuXml()
		{
			List<string> list = new List<string>();
			try
			{
				if (!this.LoadXML(this.m_strXmlPathFileName))
				{
					return list;
				}
				foreach (object obj in this.m_xmlDoc.SelectSingleNode("MYCONFIG").SelectNodes("Tabs"))
				{
					XmlNode xmlNode = (XmlNode)obj;
					if (xmlNode.Attributes["Name"].Value == "Custom")
					{
						foreach (object obj2 in xmlNode.SelectNodes("Tab"))
						{
							XmlNode xmlNode2 = (XmlNode)obj2;
							if (xmlNode2.Attributes["Name"].Value != "分割线")
							{
								list.Add(xmlNode2.Attributes["Name"].Value);
							}
						}
					}
				}
			}
			catch
			{
			}
			return list;
		}

		public static string GetCmdPath(CommandInfos commandInfos, string strXmlPathFileName)
		{
            //IEnumerator<XElement> enumerator = (from target in XElement.Load(strXmlPathFileName).Descendants("PushButton";
            //where target.Attribute("Name").Value == commandInfos.CmdName && target.Attribute("ClassName").Value == commandInfos.ClassName
            //select target).GetEnumerator())
            //{
            //    if (enumerator.MoveNext())
            //    {
            //        if (enumerator.Current.Attribute("ClassName").Value == "")
            //        {
            //            return "REVIT";
            //        }
            //        return "盈建科";
            //    }
            //}
			return null;
		}

		public bool ModifyXML(System.Windows.Controls.TreeView treeView, CommandTableInfos commandTableInfos)
		{
			XElement xelement = XElement.Load(this.m_strXmlPathFileName);
			for (int i = 0; i < commandTableInfos.TableInofList.Count; i++)
			{
				TableInfos tableInfos = commandTableInfos.TableInofList[i];
				int j = 0;
				while (j < tableInfos.CommandInfoList.Count)
				{
					CommandInfos commandInfos = tableInfos.CommandInfoList[j];
					IEnumerable<XElement> enumerable = from target in xelement.Descendants("PushButton")
					where target.Attribute("Name").Value == commandInfos.CmdName && target.Attribute("ClassName").Value == commandInfos.ClassName && target.Attribute("CommandId").Value == commandInfos.CmdId
					select target;
					if (commandInfos.LstCommandInfos.Count == 0)
					{
						IEnumerator<XElement> enumerator = enumerable.GetEnumerator();
						{
							while (enumerator.MoveNext())
							{
								XElement xelement2 = enumerator.Current;
								this.SetIsShow(commandInfos, enumerable);
							}
							goto IL_12A;
						}
						goto IL_B4;
					}
					goto IL_B4;
					IL_12A:
					j++;
					continue;
					IL_B4:
					using (List<CommandInfos>.Enumerator enumerator2 = commandInfos.LstCommandInfos.GetEnumerator())
					{
						while (enumerator2.MoveNext())
						{
							CommandInfos commandInfo = enumerator2.Current;
							IEnumerable<XElement> targetNodes = from target in xelement.Descendants("PushButton")
							where target.Attribute("Name").Value == commandInfo.CmdName && target.Attribute("ClassName").Value == commandInfo.ClassName && target.Attribute("CommandId").Value == commandInfo.CmdId
							select target;
							this.SetIsShow(commandInfo, targetNodes);
						}
					}
					goto IL_12A;
				}
			}
			xelement.Save(this.m_strXmlPathFileName);
			return true;
		}

		private void SetIsShow(CommandInfos commandInfo, IEnumerable<XElement> targetNodes)
		{
			foreach (XElement xelement in targetNodes)
			{
				if (xelement.Parent.Parent.Name == "Tab" && xelement.Parent.Parent.Attribute("Name").Value == commandInfo.TabName)
				{
					this.SetCmdTureOrFalse(commandInfo, xelement);
				}
				if (xelement.Parent.Parent.Parent.Name == "Tab" && xelement.Parent.Parent.Parent.Attribute("Name").Value == commandInfo.TabName)
				{
					this.SetCmdTureOrFalse(commandInfo, xelement);
				}
			}
		}

		private void SetCmdTureOrFalse(CommandInfos commandInfo, XElement node)
		{
			if (!commandInfo.CmdShow)
			{
				node.SetAttributeValue("IsShow", "False");
				return;
			}
			node.SetAttributeValue("IsShow", "True");
		}

		private void SetXmlCmd(TreeViewItem treeViewItem, XmlElement xmlNode)
		{
			foreach (object obj in ((IEnumerable)treeViewItem.Items))
			{
				TreeViewItem treeViewItem2 = (TreeViewItem)obj;
				XmlElement xmlElement = this.m_xmlDoc.CreateElement("PushButton");
				if (treeViewItem2.Tag.ToString() == "分割线")
				{
					xmlElement.SetAttribute("Name", "分割线");
				}
				else
				{
					(treeViewItem2.Tag as CommandInfos).SetAttribute(xmlElement);
				}
				xmlNode.AppendChild(xmlElement);
			}
		}

		private bool LoadXML(string settingFilePath)
		{
			if (File.Exists(settingFilePath))
			{
				this.m_xmlDoc = new XmlDocument();
				this.m_xmlDoc.Load(settingFilePath);
				return true;
			}
			return false;
		}

		public bool ImportOpeningByXml(out CommandTableInfos commandTableInfos, string type)
		{
			commandTableInfos = new CommandTableInfos();
			XmlReader xmlReader = null;
			if (!this.LoadXmlDocument(ref xmlReader))
			{
				return false;
			}
			try
			{
				XmlNode xmlNode = null;
				if (!this.GetXmlNodeValidItemRoot(out xmlNode))
				{
					YJKMessageBox.Show("得到XML中节点tabs时出错！", MessageBoxButtons.OK, MessageBoxIcon.Hand);
					return false;
				}
				List<TableInfos> list = new List<TableInfos>();
				foreach (object obj in xmlNode.SelectNodes("Tabs"))
				{
					XmlNode xmlNode2 = (XmlNode)obj;
					if (xmlNode2.Attributes["Name"].Value == type)
					{
						foreach (object obj2 in xmlNode2.SelectNodes("Tab"))
						{
							XmlNode xmlNode3 = (XmlNode)obj2;
							TableInfos tableInfos = new TableInfos();
							tableInfos.TableName = Convert.ToString(xmlNode3.Attributes["Name"].Value);
							try
							{
								tableInfos.Type = Convert.ToString(xmlNode3.Attributes["Type"].Value);
							}
							catch
							{
							}
							List<XmlNode> list2 = new List<XmlNode>();
							this.GetCmdNodes(xmlNode3, ref list2);
							if (list2.Count != 0)
							{
								List<CommandInfos> list3 = new List<CommandInfos>();
								foreach (XmlNode xmlNode4 in list2)
								{
									CommandInfos commandInfos = new CommandInfos();
									if (xmlNode4.ChildNodes.Count > 0)
									{
										commandInfos.LstCommandInfos = this.GetChildrenNode(xmlNode4, tableInfos.TableName);
										commandInfos.CmdName = xmlNode4.Attributes["Name"].Value;
									}
									else
									{
										commandInfos.ImportByXmlNode(xmlNode4, tableInfos.TableName);
									}
									list3.Add(commandInfos);
								}
								tableInfos.CommandInfoList = list3;
								list.Add(tableInfos);
							}
						}
					}
				}
				commandTableInfos.TableInofList = list;
			}
			catch (Exception)
			{
			}
			xmlReader.Close();
			return true;
		}

		private List<CommandInfos> GetChildrenNode(XmlNode xmlNode, string tabName)
		{
			List<CommandInfos> list = new List<CommandInfos>();
			foreach (object obj in xmlNode.ChildNodes)
			{
				XmlNode xmlNode2 = (XmlNode)obj;
				CommandInfos commandInfos = new CommandInfos();
				commandInfos.ImportByXmlNode(xmlNode2, tabName);
				commandInfos.CmdId = xmlNode2.Attributes["CommandId"].Value;
				list.Add(commandInfos);
			}
			return list;
		}

		private void GetCmdNodes(XmlNode xnTab, ref List<XmlNode> lstXmlNodes)
		{
			if (xnTab == null)
			{
				return;
			}
			if (xnTab.ChildNodes.Count == 0 && xnTab.Name == "PushButton")
			{
				lstXmlNodes.Add(xnTab);
				return;
			}
			if (xnTab.ChildNodes.Count != 0 && xnTab.Name == "GroupButton")
			{
				lstXmlNodes.Add(xnTab);
				return;
			}
			foreach (object obj in xnTab.ChildNodes)
			{
				XmlNode xnTab2 = (XmlNode)obj;
				this.GetCmdNodes(xnTab2, ref lstXmlNodes);
			}
		}

		private bool GetXmlNodeValidItemRoot(out XmlNode root)
		{
			bool result;
			try
			{
				root = this.m_xmlDoc.SelectSingleNode("MYCONFIG");
				result = true;
			}
			catch (Exception)
			{
				root = null;
				result = false;
			}
			return result;
		}

		private bool LoadXmlDocument(ref XmlReader reader)
		{
			bool result;
			try
			{
				if (!File.Exists(this.m_strXmlPathFileName))
				{
					YJKMessageBox.Show("无效的路径", MessageBoxButtons.OK, MessageBoxIcon.Hand);
					result = false;
				}
				else
				{
					this.m_xmlDoc = new XmlDocument();
					XmlReaderSettings xmlReaderSettings = new XmlReaderSettings();
					xmlReaderSettings.IgnoreComments = true;
					reader = XmlReader.Create(this.m_strXmlPathFileName, xmlReaderSettings);
					this.m_xmlDoc.Load(reader);
					result = true;
				}
			}
			catch (Exception ex)
			{
				YJKMessageBox.Show("加载XML文档失败：\n" + ex.Message, MessageBoxButtons.OK, MessageBoxIcon.Hand);
				result = false;
			}
			return result;
		}

		public static XmlDocument MergeXml(string strRevitShortcuts, string strConfiguration)
		{
			XmlDocument xmlDocument = new XmlDocument();
			xmlDocument.Load(strRevitShortcuts);
			XmlNode documentElement = xmlDocument.DocumentElement;
			XmlDocument xmlDocument2 = new XmlDocument();
			xmlDocument2.Load(strConfiguration);
			XmlNode xmlNode = xmlDocument2.SelectSingleNode("MYCONFIG");
			XmlElement xmlElement = xmlDocument2.CreateElement("Shortcuts");
			xmlNode.AppendChild(xmlElement);
			foreach (object obj in documentElement.ChildNodes)
			{
				XmlNode node = (XmlNode)obj;
				XmlNode newChild = xmlDocument2.ImportNode(node, true);
				xmlElement.AppendChild(newChild);
			}
			return xmlDocument2;
		}

		public static XmlDocument SplitXml(string strConfiguration, string strKeyFileName)
		{
			XmlDocument xmlDocument = new XmlDocument();
			xmlDocument.Load(strConfiguration);
			XmlElement documentElement = xmlDocument.DocumentElement;
			XmlDocument xmlDocument2 = new XmlDocument();
			XmlElement xmlElement = xmlDocument2.CreateElement("Shortcuts");
			xmlDocument2.AppendChild(xmlElement);
			foreach (object obj in documentElement.SelectSingleNode("Shortcuts").ChildNodes)
			{
				XmlNode node = (XmlNode)obj;
				XmlNode newChild = xmlDocument2.ImportNode(node, true);
				xmlElement.AppendChild(newChild);
			}
			xmlDocument2.Save(strKeyFileName);
			documentElement.RemoveChild(documentElement.SelectSingleNode("Shortcuts"));
			return xmlDocument;
		}

		private string m_strXmlPathFileName;

		private XmlDocument m_xmlDoc;
	}
}
